package com.esunny.resourcevisualization.email;

import com.esunny.resourcevisualization.domain.entity.User;
import com.esunny.resourcevisualization.manage.SystemConfigManage;
import com.esunny.resourcevisualization.manage.UserManage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @ClassName: MailController
 * @Description: 测试邮件发送
 * @Author: hp
 * @Date: 2021/3/8 14:40
 * @version: 1.0
 */
@Component
public class MailProxy {

    @Resource
    private JavaMailSender mailSender;

    @Resource
    private UserManage userManage;

    @Resource
    private SystemConfigManage systemConfigManage;

    private Logger LOGGER = LoggerFactory.getLogger(MailProxy.class);

    /**
     * 发送邮件
     * @param from 发送方
     * @param to 接收方
     * @param subject 主题
     * @param text 内容
     * @return 发送是否成功
     */
    public boolean sendTextMail(String from,String to,String subject,String text){
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom(from);
            mailMessage.setTo(to);
            mailMessage.setSubject(subject);
            mailMessage.setText(text);

            mailSender.send(mailMessage);
        }catch (Exception e){
            LOGGER.error(String.valueOf(e.getStackTrace()));
            return false;
        }

        return true;
    }

    /**
     * 通过用户名发送邮件
     * @param username 用户名
     * @param subject 主题
     * @param text 内容
     * @return 是否发送成功
     */
    public boolean sendTextMailByUsername(String username,String subject,String text){
        User userInfo = userManage.getUserByName(username);

        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom("1361585641@qq.com");
            mailMessage.setTo(userInfo.getEmail());
            mailMessage.setSubject(subject);
            mailMessage.setText(text);

            mailSender.send(mailMessage);
        }catch (Exception e){
            LOGGER.error(String.valueOf(e.getStackTrace()));
            return false;
        }

        return true;
    }

    /**
     * 给管理员发送邮件
     * @param subject 主题
     * @param text 内容
     * @return 是否发送成功
     */
    public boolean sendTextMailToAdmin(String subject,String text){
        try {
            String[] admins = systemConfigManage.getConfigByKey("receiveMessageAdmin").getValue().split(",");
            for (String admin : admins) {
                sendTextMailByUsername(admin, subject,text);
            }
        }catch (Exception e){
            LOGGER.error(String.valueOf(e.getStackTrace()));
            return false;
        }

        return true;
    }
}
